package features.advance.jdk.jvm;

import java.io.Serializable;
import java.sql.Connection;
import java.util.LinkedList;
import java.util.Queue;

/**
 * @author LIN
 * @date 2021-07-14
 */
public class Lock implements Serializable {

    private Object a = "1";
    private Object b = "2";
    private static Lock demo = null;//静态变量，多个线程之间不可见
    private static String tmp = "a";
    private int free = 0;
    private Queue<Connection> cacheConnections = new LinkedList<>();

    public static Lock getInstance(){
        if(demo == null){
            tmp = "aa";
            demo = new Lock();
            return demo;
        }else {
            return demo;
        }
    }

    // 死锁
    public void callAB() {
        synchronized (b){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (a){
                System.out.println("callAB");
            }
        }
    }

    public void executeAB(){
        synchronized (a){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (b){
                System.out.println("executeAB");
            }
        }
    }

    public Connection get(){
        synchronized (this){
            if(free >0){
                free--;
                return cacheConnections.poll();
            }else{
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("等待结束");
                free--;
                return cacheConnections.poll();
            }

        }
    }

    public void close(Connection conn){
        synchronized (this){
            free++;
            cacheConnections.offer(conn);
            this.notifyAll();
        }

    }

    // CAS机制 compare and swap

}
